package jp.sourceforge.akjrcp.ffmpeg;

import com.akjava.lib.standards.process.ProcessMonitor;
import com.akjava.lib.standards.process.ProcessPrinter;
import com.akjava.lib.standards.process.SimpleProcessPrinter;

import java.io.IOException;



public class FFMpegJpegPipeReader implements Runnable{
	JpegPipeReader jpegPipeReader;
	private String[] command;
	private Process process;
	ProcessListener processListener;

	ProcessPrinter processPrinter=new SimpleProcessPrinter();
	public FFMpegJpegPipeReader(String ffmpegPath,String inputPath,String options[]){
		command=FFMpegCommandUtil.makeJpegOutputPipeCommand(ffmpegPath,inputPath,options);
		jpegPipeReader=new JpegPipeReader();
		}
	public ProcessPrinter getProcessPrinter() {
		return processPrinter;
	}

	public void setProcessPrinter(ProcessPrinter processPrinter) {
		this.processPrinter = processPrinter;
	}
	public void run() {
		Runtime runtime=Runtime.getRuntime();
		try {
			process = runtime.exec(command);
			
			//DoNothingProcessPrinter printer=new DoNothingProcessPrinter();
			ProcessMonitor monitor=new ProcessMonitor(process,processPrinter);
			monitor.setMonitorInput(false);//stop read input.
			monitor.startMonitor();
			
			jpegPipeReader.setInputStream(process.getInputStream());
			
			if(processListener!=null){
				processListener.started();
			}
			try {
				process.waitFor();
				synchronized(this){
				jpegPipeReader.setDone(true);
				}
				
				
				if(processListener!=null){
					processListener.finished();
				}
				//process.destroy();//
				//log.inforead process finished");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void cancel(){
		if(process!=null){
			process.destroy();
		}
	}
	
	public void close() throws IOException{
		if(jpegPipeReader!=null){
			jpegPipeReader.close();
		}
	}

	public String[] getCommand() {
		return command;
	}

	public void setCommand(String[] command) {
		this.command = command;
	}



	public Process getProcess() {
		return process;
	}

	public void setProcess(Process process) {
		this.process = process;
	}

	public ProcessListener getProcessListener() {
		return processListener;
	}

	public void setProcessListener(ProcessListener processListener) {
		this.processListener = processListener;
	}

	public JpegPipeReader getJpegPipeReader() {
		return jpegPipeReader;
	}

	public void setJpegPipeReader(JpegPipeReader jpegPipeReader) {
		this.jpegPipeReader = jpegPipeReader;
	}


}
